package com.kws.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.dao.Express100Info;
import com.kws.common.config.dao.rq.QueryExpress100Rq;
import com.kws.common.core.domain.R;
import com.kws.common.core.exception.ServiceException;
import com.kws.system.domain.info.GainLogisticsInfo;
import com.kws.system.domain.info.QueryLogisticsDetailsInfo;
import com.kws.system.domain.info.QueryLogisticsScheduleInfo;
import com.kws.system.domain.payment.TbOrder;
import com.kws.system.domain.vo.QueryLogisticsScheduleRq;
import com.kws.system.feign.ExpressDeliveryService;
import com.kws.system.mapper.LogisticsScheduleMapper;
import com.kws.system.service.LogisticsScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <b>LogisticsScheduleServiceImpl</b>
 *
 * @description: LogisticsScheduleServiceImpl <br>
 * @date: 2024/11/22 09:57 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class LogisticsScheduleServiceImpl extends ServiceImpl<LogisticsScheduleMapper,TbOrder> implements LogisticsScheduleService {
    private static final Logger logger = LoggerFactory.getLogger(LogisticsScheduleServiceImpl.class);

    @Autowired
    private ExpressDeliveryService expressDeliveryService;

    @Override
    public Page<QueryLogisticsScheduleInfo> queryLogisticsSchedulePage(QueryLogisticsScheduleRq rq) {
        Page<QueryLogisticsScheduleInfo> page = new Page<>(rq.getPageNum(), rq.getPageSize());
        Page<QueryLogisticsScheduleInfo> pageInfo = baseMapper.queryLogisticsSchedulePage(page,rq);
        return pageInfo;
    }

    @Override
    public void gainLogisticsStatus() {
        List<GainLogisticsInfo> orderList = baseMapper.gainLogisticsStatus();
        if (CollectionUtil.isNotEmpty(orderList)){
            //获取所有快递列表
            List<String> trackingNumberList = orderList.stream().map(GainLogisticsInfo::getTrackingNumber).collect(Collectors.toList());
            List<String> list = trackingNumberList.stream().distinct().collect(Collectors.toList());
            //获取分组列表
            Map<String, List<GainLogisticsInfo>> map = orderList.stream().collect(Collectors.groupingBy(GainLogisticsInfo::getTrackingNumber));
            list.forEach(item -> {
                GainLogisticsInfo tbOrder = map.get(item).get(0);
                QueryExpress100Rq requestJson = new QueryExpress100Rq();
                requestJson.setCom(tbOrder.getExpressCompany());
                requestJson.setNum(tbOrder.getTrackingNumber());
                requestJson.setPhone(tbOrder.getConsigneePhone());
                int index = tbOrder.getCompanyAddress().indexOf("市");
                requestJson.setFrom(tbOrder.getCompanyAddress().substring(0,index+1));
                int index1 = tbOrder.getAddress().indexOf("市");
                requestJson.setTo(tbOrder.getAddress().substring(0,index1+1));
                R<Express100Info> express = expressDeliveryService.queryExpressDeliveryPage(requestJson);
                if (R.FAIL == express.getCode())
                {
                    logger.info("获取物流信息失败：trackingNumber="+requestJson.getNum()+"失败原因："+express.getMsg());
                }
                Express100Info data = express.getData();
                if (null != data) {
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("tracking_number", item);
                    updateWrapper.set("logistics_status", data.getState());
                    updateWrapper.set("current_address",data.getRouteInfo().getCur().getName());
                    updateWrapper.set("estimated_time",data.getArrivalTime());
                    baseMapper.update(null,updateWrapper);
                }
            });

        }
    }

    @Override
    public QueryLogisticsDetailsInfo queryLogisticsDetailsById(Long id) {
        GainLogisticsInfo gainLogistics = baseMapper.gainLogisticsStatusById(id);
        QueryLogisticsDetailsInfo info = baseMapper.queryLogisticsDetailsById(id);
        if (null != gainLogistics){
            QueryExpress100Rq requestJson = new QueryExpress100Rq();
            requestJson.setCom(gainLogistics.getExpressCompany());
            requestJson.setNum(gainLogistics.getTrackingNumber());
            requestJson.setPhone(gainLogistics.getConsigneePhone());
            int index = gainLogistics.getCompanyAddress().indexOf("市");
            requestJson.setFrom(gainLogistics.getCompanyAddress().substring(0,index+1));
            int index1 = gainLogistics.getAddress().indexOf("市");
            requestJson.setTo(gainLogistics.getAddress().substring(0,index1+1));
            R<Express100Info> express = expressDeliveryService.queryExpressDeliveryPage(requestJson);
            if (R.FAIL != express.getCode())
            {
                info.setTrailUrl(express.getData().getTrailUrl());
                info.setLogisticsList(express.getData().getData());
            }
        }
        return info;
    }
}
